package com.ssn.service.impl;

import com.ssn.dao.TagRepository;
import com.ssn.exception.NotFoundException;
import com.ssn.po.Tag;
import com.ssn.po.Type;
import com.ssn.service.ITagService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TagServiceImpl implements ITagService {
    @Resource
    private TagRepository tagRepository;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }
    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagRepository.getOne(id);
    }
    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }
    private List<Long> convertToList(String ids){
        List<Long> res = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idArr = ids.split(",");
            for (String id:idArr) {
                res.add(Long.parseLong(id));
            }
        }
        return res;
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagRepository.findAllById(convertToList(ids));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0, size, sort);
        return tagRepository.findTop(pageable);
    }


    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRepository.findById(id).orElse(null);
        if (t == null) throw new NotFoundException("不存在该类型");
        BeanUtils.copyProperties(tag,t);
        return tagRepository.save(t);
    }
    @Transactional
    @Override
    public void deteleTag(Long id) {
        tagRepository.deleteById(id);
    }
    @Transactional
    @Override
    public Tag findTagByName(String name) {
        return tagRepository.findTagByName(name);
    }
}
